namespace EyeOpen.Trial.Data
{
	using System.Data.Common;
	using System.Data.Entity;
	using System.Data.Entity.ModelConfiguration.Conventions;

	using EyeOpen.Trial.Domain;

	public class ApplicationUnitOfWorkEf 
		: DbContext, IApplicationUnitOfWork
	{
		public ApplicationUnitOfWorkEf(string providerInvariantName, string connectionString)
			: base(CreateConnection(providerInvariantName, connectionString), true)
		{
		}

		public IRepository<Application> ApplicationRepository
		{
			get
			{
				return
					Repository(Set<Application>());
			}
		}

		public void Commit()
		{
			SaveChanges();
		}

		protected override void OnModelCreating(DbModelBuilder modelBuilder)
		{
			modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

			modelBuilder.Entity<Application>();
		}

		private static DbConnection CreateConnection(string providerInvariantName, string connectionString)
		{
			var connection = 
				DbProviderFactories
					.GetFactory(providerInvariantName)
					.CreateConnection();

			connection.ConnectionString = connectionString;
			return connection;
		}

		private IRepository<T> Repository<T>(DbSet<T> dbSet) 
			where T : class
		{
			return
				new Repository<T>(this, dbSet);
		}
	}
}